package leetcode.binaryTree;

import datastructure.tree.TreeNode;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;

/**
 * @Description: https://leetcode.cn/problems/symmetric-tree/
 *
 * 给你一个二叉树的根节点 root ， 检查它是否轴对称。
 * 草稿(旧) 10 11
 *
 * @Author Ammar
 * @Create 2023/4/3 22:47
 */
public class _101_对称二叉树 {
    public static void main(String[] args) {
        TreeNode<Integer> root = new TreeNode<>(1, null);
        TreeNode<Integer> left = new TreeNode<>(2, null);
        TreeNode<Integer> right = new TreeNode<>(2, null);
        root.left = left;
        root.right = right;
        left.left = new TreeNode<>(3, null);
        left.right = new TreeNode<>(4, null);
        right.left = new TreeNode<>(4, null);
        right.right = new TreeNode<>(3, null);
        System.out.println(isSymmetric1(root));
    }

    // 递归
    public static boolean isSymmetric(TreeNode root) {
        if (root == null) return true;
        // 判断左右子树是否对称
        return isSymmetric(root.left, root.right);
    }

    // 判断左右子树是否对称
    public static boolean isSymmetric(TreeNode left, TreeNode right) {
        // 左右子树都为空
        if (left == null && right == null) return true;
        // 左右子树有一个为空
        if (left == null || right == null) return false;
        // 左子树与右子树的值不相等
        if (left.val != right.val) return false;
        // 如果左子树的左子树与右子树的右子树对称，且左子树的右子树与右子树的左子树对称，则左右子树对称
        return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
    }

    // 迭代
    public static boolean isSymmetric1(TreeNode root) {
        // 如果根节点为空，则对称
        if (root == null) return true;
        // 用队列存储左右子树
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root.left);
        stack.add(root.right);
        while (!stack.isEmpty()) {
            TreeNode left = stack.pop();
            TreeNode right = stack.pop();
            // 左右子树都为空则继续
            if (left == null && right == null) continue;
            // 左右子树有一个为空则不对称
            if (left == null || right == null) return false;
            // 左右子树的值不相等则不对称
            if (left.val != right.val) return false;
            // 依次将 left.left, right.right, left.right, right.left 压入栈中
            stack.add(left.left);
            stack.add(right.right);
            stack.add(left.right);
            stack.add(right.left);
        }
        return true;
    }
}
